package modulos;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;

import auxiliary.Constants;
import auxiliary.Database;

public class PanelFuncionario extends JPanel implements ActionListener {

	ArrayList<ArrayList<String>> listOfFuncionarios;
	ArrayList<ArrayList<String>> listOfMaquinaria;
	Database db;
	ArrayList<JRadioButton> radiobuttons;
	ButtonGroup group;
	JPanel radioPanel;
	int currentButton;
	JTable jt;
	TableModelFuncionario ftm;
	PanelFuncionario panel;
	ImageIcon imageicon,redicon,greenicon,add,delete,modify;
	JLabel imagelabel;

	// FuncionarioButtonHandler handler;

	public PanelFuncionario() {

		panel = this;
		db = new Database();
		
		listOfFuncionarios = db.retrieveFuncionarios();
		currentButton = 0;
		String[] strArray = new String[listOfFuncionarios.size()];

		ftm = new TableModelFuncionario();
		jt = new JTable(ftm);
		updateTable();
		setColumnWidth();

		URL imgURL = ClassLoader.getSystemResource("images/back.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);

		// String dir = System.getProperty("user.dir");
		imageicon = new ImageIcon(image);
		imagelabel = new JLabel(imageicon);
		
		imgURL = ClassLoader.getSystemResource("images/red.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		redicon = new ImageIcon(image);
		
		Image img = redicon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		redicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/green.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		greenicon = new ImageIcon(image);
		
		img = greenicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		greenicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/add.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		add = new ImageIcon(image);
		
		img = add.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		add = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/delete.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		delete = new ImageIcon(image);
		
		img = delete.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		delete = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/modify.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		modify = new ImageIcon(image);
		
		img = modify.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		modify = new ImageIcon(newimg);

		radiobuttons = new ArrayList<JRadioButton>();
		for (Integer i = 0; i < listOfFuncionarios.size(); i++) {
			radiobuttons.add(new JRadioButton());
			radiobuttons.get(i).setSize(20, 20);

			radiobuttons.get(i).setActionCommand(i.toString());
			radiobuttons.get(i).addActionListener(this);
			// System.out.println(radiobuttons.get(i).getActionCommand());
			// Group the radio buttons.
			radiobuttons.get(0).setSelected(true);
		}

		group = new ButtonGroup();

		radioPanel = new JPanel();
		radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));

		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		for (int i = 0; i < listOfFuncionarios.size(); i++) {

			group.add(radiobuttons.get(i));
			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		jt.setEnabled(false);
		jt.setRowHeight(22);
		jt.getTableHeader().setReorderingAllowed(false);
		jt.getTableHeader().setFont(new Font("Dialog", Font.BOLD, 14));
		
		JScrollPane jsp = new JScrollPane(jt);
		jsp.setPreferredSize(new Dimension(900, 475));

		JButton addbutton = new JButton("Agregar",add);
		addbutton.setActionCommand(Constants.FUNCIONARIO_AGREGAR);
		addbutton.addActionListener(this);

		JButton removebutton = new JButton("Eliminar",delete);
		removebutton.setActionCommand(Constants.FUNCIONARIO_ELIMINAR);
		removebutton.addActionListener(this);

		JButton modifybutton = new JButton("Modificar",modify);
		modifybutton.setActionCommand(Constants.FUNCIONARIO_MODIFICAR);
		modifybutton.addActionListener(this);

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		// JPanel bottomPanel = new JPanel(new BorderLayout());
		JPanel topPanel = new JPanel(new BorderLayout());

		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(addbutton, BorderLayout.WEST);
		buttonPanel.add(modifybutton, BorderLayout.CENTER);
		buttonPanel.add(removebutton, BorderLayout.EAST);
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(imagelabel, BorderLayout.EAST);

		topPanel.add(jsp, BorderLayout.CENTER);
		topPanel.add(radioPanel, BorderLayout.WEST);

		this.setLayout(new BorderLayout());
		this.add(topPanel, BorderLayout.NORTH);
		this.add(buttonPanel, BorderLayout.SOUTH);

		this.setVisible(true);

	}

	private void setColumnWidth() {

		jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		jt.getColumnModel().getColumn(0).setPreferredWidth(90);
		jt.getColumnModel().getColumn(1).setPreferredWidth(75);
		jt.getColumnModel().getColumn(2).setPreferredWidth(75);
		jt.getColumnModel().getColumn(3).setPreferredWidth(75);
		jt.getColumnModel().getColumn(4).setPreferredWidth(50);
		jt.getColumnModel().getColumn(5).setPreferredWidth(50);
		jt.getColumnModel().getColumn(6).setPreferredWidth(50);
		jt.getColumnModel().getColumn(7).setPreferredWidth(50);
		jt.getColumnModel().getColumn(8).setPreferredWidth(50);
		jt.getColumnModel().getColumn(9).setPreferredWidth(50);
		jt.getColumnModel().getColumn(10).setPreferredWidth(50);
		jt.getColumnModel().getColumn(11).setPreferredWidth(50);
		jt.getColumnModel().getColumn(12).setPreferredWidth(1000);
	}

	void addRadioButton() {
		Integer buttonindex = listOfFuncionarios.size() - 1;

		radiobuttons.add(new JRadioButton());
		radiobuttons.get(buttonindex).setSize(20, 20);
		radiobuttons.get(buttonindex).setActionCommand(buttonindex.toString());
		radiobuttons.get(buttonindex).addActionListener(this);

		group.add(radiobuttons.get(buttonindex));
		//radioPanel.add(radiobuttons.get(buttonindex));
		
		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());

		}
		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	void deleteRadioButton(int button) {
		final int curr = button;

		//radioPanel.remove(radiobuttons.get(curr));
		group.remove(radiobuttons.get(curr));
		radiobuttons.remove(curr);

		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}
		
		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());

		}
		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	public void updateTable() {
		ftm.updateTable();
		setColumnWidth();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		if (command == Constants.FUNCIONARIO_AGREGAR) {
			String[] labels = { "Codigo", "Nombre", "Apellido", "Cargo", "Dispensacion", "Produccion", "Llenado",
					"Loteado", "Etiqueteado", "Bandas", "Empacado", "Limpieza",
					"Maquinas" };
			int[] widths = { 10, 15, 15, 20, 10, 10, 10, 10, 10, 10, 10, 10,
					10, 10, 10, 10, 10, 10 };
			String[] descs = { "Codigo", "Nombre", "Apellido", "Cargo", "Dispensacion", "Produccion", "Llenado",
					"Loteado", "Etiqueteado", "Bandas", "Empacado", "Limpieza",
					"Maquinas" };

			AgregarFuncionario agregar = new AgregarFuncionario(jt, labels,
					widths, descs, Constants.getParentFrame(this));
			// agregar.setVisible(true);

		} else if (command == Constants.FUNCIONARIO_ELIMINAR) {

			String[][] allvalues = Constants
					.arrayListToString(listOfFuncionarios);

			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));
			String[] values = list.toArray(new String[0]);

			db.deleteFuncionario(values);

			listOfFuncionarios = db.retrieveFuncionarios();

			updateTable();
			deleteRadioButton(currentButton);
			radioPanel.revalidate();
			radioPanel.repaint();

			// panel.revalidate();
			// panel.repaint();

		} else if (command == Constants.FUNCIONARIO_MODIFICAR) {

			int labelsLength;

			String[][] allvalues = Constants
					.arrayListToString(listOfFuncionarios);

			int size = allvalues[currentButton].length;

			// System.out.println("size=" + size);

			String[] labels = { "Codigo", "Nombre", "Apellido", "Cargo", "Dispensacion", "Produccion", "Llenado",
					"Loteado", "Etiqueteado", "Bandas", "Empacado", "Limpieza",
					"Maquinas" };
			int[] widths = { 10, 15, 15, 20, 10, 10, 10, 10, 10, 10, 10, 10,
					10, 10, 10, 10, 10, 10 };
			String[] descs = { "Codigo", "Nombre", "Apellido", "Cargo", "Dispensacion", "Produccion", "Llenado",
					"Loteado", "Etiqueteado", "Bandas", "Empacado", "Limpieza",
					"Maquinas" };

			// labelsLength = 7;

			/*
			 * for (int i = 7; i < size; i++) { String array[] =
			 * allvalues[currentButton][i].split(","); //
			 * System.out.println(allvalues[currentButton][i]); // labelsLength
			 * += array.length; labels = (String[]) Constants.concat(labels, new
			 * String[] { allvalues[currentButton][i] }); descs = (String[])
			 * Constants.concat(descs, new String[] {
			 * allvalues[currentButton][i] }); }
			 */
			// System.out.println("labels count" + labels.length);
			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));
			String[] values = list.toArray(new String[0]);
			// System.out.println(list);
			ModificarFuncionario agregar = new ModificarFuncionario(labels,
					widths, descs, values, labels.length, Constants
							.getParentFrame(this));
		} else {
			currentButton = Integer.valueOf(e.getActionCommand());
		}
	}

	public class AgregarFuncionario extends JDialog implements ActionListener {

		Container contentPane;
		JPanel form;
		JTextField[] fields;
		JList list;
		// FuncionarioPanel panel;
		AgregarFuncionario agregarFrame;
		String[] maquinariaIds;
		JCheckBox boxes[];

		public AgregarFuncionario(JTable jt, final String[] labels,
				final int[] widths, final String[] tips, JFrame parent) {
			super(parent, "Agregar Funcionario",
					Dialog.ModalityType.DOCUMENT_MODAL);

			agregarFrame = this;
			//db = new Database();
			contentPane = getContentPane();
			form = new JPanel(new BorderLayout());

			boxes = new JCheckBox[8];

			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));
			JPanel listform = new JPanel();
			// listform.setLayout(new BoxLayout(listform, BoxLayout.X_AXIS));

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion del Funcionario");
			form.setBorder(border);

			Border border2 = BorderFactory.createTitledBorder(loweredbevel,
					"Maquinas Asignadas");
			listform.setBorder(border2);

			JPanel buttonPanel = new JPanel();

			JPanel labelPanel = new JPanel(new GridLayout(labels.length - 1, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length - 1, 1));

			fieldPanel.setBorder(grayborder);

			form.add(labelPanel, BorderLayout.WEST);
			form.add(Box.createRigidArea(new Dimension(10, 25)));
			form.add(fieldPanel, BorderLayout.CENTER);

			JPanel listLabelPanel = new JPanel(new GridLayout(1, 1));
			JPanel listPanel = new JPanel(new GridLayout(1, 1));

			// listform.add(listLabelPanel, BorderLayout.WEST);
			listform.add(Box.createRigidArea(new Dimension(10, 25)));
			listform.add(listPanel, BorderLayout.CENTER);

			fields = new JTextField[labels.length];

			listOfMaquinaria = db.retrieveMaquinaria();

			for (int i = 0; i < labels.length - 1; i++) {
				fields[i] = new JTextField();
				if (i < tips.length)
					fields[i].setToolTipText(tips[i]);
				if (i < widths.length)
					fields[i].setColumns(widths[i]);

				JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
				lab.setLabelFor(fields[i]);
				labelPanel.add(lab);
				JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
				if (i >= 4 && i <= 11) {
					boxes[i - 4] = new JCheckBox();
					p.add(boxes[i - 4]);
				} else {
					p.add(fields[i]);
				}
				fieldPanel.add(p);
			}

			JLabel lab = new JLabel(labels[labels.length - 1], JLabel.RIGHT);
			lab.setLabelFor(fields[labels.length - 1]);
			listLabelPanel.add(lab);

			// JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
			// p.add(fields[i]);
			// fieldPanel.add(p);
			JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));

			list = new JList(Constants.arrayListToStringSelect(
					listOfMaquinaria, 1, 2));
			maquinariaIds = Constants.arrayListToStringSelect(listOfMaquinaria,
					0, 1);

			list.setFixedCellWidth(175);
			list.setVisibleRowCount(5);
			JScrollPane scrollpane = new JScrollPane(list);

			p.add(scrollpane);
			listPanel.add(p, BorderLayout.CENTER);

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.FUNCIONARIO_AGREGAR_CANCELAR);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.FUNCIONARIO_AGREGAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);

			contentPane.add(form, BorderLayout.NORTH);
			contentPane.add(listform, BorderLayout.CENTER);
			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);

			pack();

			setVisible(true);
		}

		public void actionPerformed(ActionEvent e) {
			ArrayList<String> funcionarioData = new ArrayList<String>();
			ArrayList<String> maquinariaData = new ArrayList<String>();

			String command = e.getActionCommand();
			if (command == Constants.FUNCIONARIO_AGREGAR_CONFIRMACION) {
				boolean validcodigo = true;
				boolean validdisponibilidad = true;
				boolean validtiempomuerto = true;
				boolean indicescheck = true;

				try {
					Integer.parseInt(fields[0].getText());

				} catch (Exception exp) {
					validcodigo = false;
				}

				try {
					Integer.parseInt(fields[4].getText());

				} catch (Exception exp) {
					validdisponibilidad = false;
				}

				try {
					Integer.parseInt(fields[5].getText());

				} catch (Exception exp) {
					validtiempomuerto = false;
				}

				if (list.getSelectedIndices().length == 0) {
					indicescheck = false;
				}

				if (validcodigo
						&& indicescheck) {

					for (int i = 0; i < fields.length - 1; i++) {
						if (i >= 4 && i <= 11) {
							funcionarioData.add(new Boolean(boxes[i - 4]
									.isSelected()).toString());
						} else {
							funcionarioData.add(fields[i].getText());
						}
					}

					int[] indices = list.getSelectedIndices();

					for (int i = 0; i < list.getSelectedIndices().length; i++) {
						maquinariaData.add(maquinariaIds[indices[i]]);
						// productoData.add(fields[i].getText());
					}

					db.insertFuncionario(funcionarioData, maquinariaData);
					listOfFuncionarios = db.retrieveFuncionarios();

					updateTable();
					addRadioButton();
					radioPanel.revalidate();

					agregarFrame.dispose();

				} else {

					JOptionPane
							.showMessageDialog(
									new JFrame(),
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validcodigo ? ""
													: "- Ingrese un numero valido para Codigo\n")
											+ /*
											 * (validdisponibilidad ? "" :
											 * "- Ingrese un numero valido para Disponibilidad\n"
											 * ) + (validtiempomuerto ? "" :
											 * "- Ingrese un numero valido para Tiempo Muerto\n"
											 * ) +
											 */(indicescheck ? ""
													: "- Seleccione al menos una maquina\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
			} else if(command.equals(Constants.FUNCIONARIO_AGREGAR_CANCELAR)) {
				agregarFrame.dispose();
			}
		}
	}

	public class ModificarFuncionario extends JDialog implements ActionListener {

		Container contentPane;
		JPanel form;
		JTextField[] fields;
		String hiddenfield;
		ArrayList<JTextField> secondaryfields;
		ArrayList<JCheckBox> secondarycheckboxes;
		// Database db;
		ModificarFuncionario modificarFrame;
		ArrayList<String> maquinariaValues;
		JCheckBox boxes[];

		public ModificarFuncionario(final String[] labels, final int[] widths,
				final String[] tips, final String[] values,
				final int labelsLength, JFrame parent) {

			super(parent, "Modificar Funcionario",
					Dialog.ModalityType.DOCUMENT_MODAL);

			// db = new Database();
			modificarFrame = this;
			contentPane = getContentPane();
			form = new JPanel(new BorderLayout());
			boxes = new JCheckBox[9];

			String[][] allvalues = Constants
					.arrayListToString(listOfFuncionarios);
			maquinariaValues = new ArrayList<String>();
			secondaryfields = new ArrayList<JTextField>();
			secondarycheckboxes = new ArrayList<JCheckBox>();

			int id = Integer.valueOf(allvalues[currentButton][0]);

			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));
			JPanel form2 = new JPanel();
			form2.setLayout(new BoxLayout(form2, BoxLayout.X_AXIS));

			JPanel buttonPanel = new JPanel();

			// System.out.println("labelslength= " + labelsLength);
			JPanel labelPanel = new JPanel(new GridLayout(labels.length - 1, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length - 1, 1));
			JPanel labelPanel2 = new JPanel();
			JPanel fieldPanel2 = new JPanel();

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion del Funcionario");
			form.setBorder(border);

			Border border2 = BorderFactory.createTitledBorder(loweredbevel,
					"Maquinas Asignadas");
			form2.setBorder(border2);

			fieldPanel.setBorder(grayborder);

			form.add(labelPanel);
			form.add(Box.createRigidArea(new Dimension(10, 25)));
			form.add(fieldPanel);

			JPanel temppanel = new JPanel();
			JScrollPane scrollpane = new JScrollPane(temppanel);
			temppanel.setLayout(new BoxLayout(temppanel, BoxLayout.X_AXIS));

			// JPanel temppanel = new JPanel();

			// temppanel.add(labelPanel2);
			// temppanel.add(Box.createRigidArea(new Dimension(10, 25)));
			// temppanel.add(fieldPanel2);

			fields = new JTextField[labels.length];

			hiddenfield = values[0];

			//String maquinariaLabel = "---- Maquinas Produccion ---";

			
			ArrayList<ArrayList<String>> listOfMaquinaria = db.retrieveMaquinaria();
			
			String[] maquinariaIds = Constants.arrayListToStringSelect(listOfMaquinaria,
					0, 1);
			
			String[] maquinariaNames = Constants.arrayListToStringSelect(
					listOfMaquinaria, 1, 2);
			
			ArrayList<String> selectedMaquinariaIds = db.getAllMaquinariaValuesForFuncionario(id,0);
			
			
			int lengthMaqValues = 0;

			for (int i = 0; i < labels.length; i++) {
				if (i == labels.length - 1) {

					fields[i] = new JTextField();

					String array[] = values[i + 1].split(",");
					
					lengthMaqValues += array.length;

					if (i < tips.length)
						fields[i].setToolTipText(tips[i]);
					if (i < widths.length)
						fields[i].setColumns(widths[i]);

					fields[i].setText(values[i + 1]);

					labelPanel2.setLayout(new GridLayout(/*array.length*/maquinariaNames.length, 1));
					fieldPanel2.setLayout(new GridLayout(/*array.length*/maquinariaNames.length, 1));
	
					for (int j = 0; j < /*array.length */ maquinariaIds.length; j++) {
						
						secondarycheckboxes.add(new JCheckBox());

						maquinariaValues.add(maquinariaIds[j]);
						
						for(int k=0;k<selectedMaquinariaIds.size();k++) {
							if(maquinariaIds[j].equals(selectedMaquinariaIds.get(k))) {
								secondarycheckboxes.get(secondarycheckboxes.size() - 1)
								.setSelected(true);
								break;
							}
						}

						

						//String maq = db.getMaquinariaValuesForFuncionario(id,
						//		0, j);
						
						//System.out.println("maqvalues" + db.getMaquinariaValuesForFuncionario(id,
						//		0, j));

						//maquinariaValues.add(maq);

						JLabel lab = new JLabel(/*array[j]*/maquinariaNames[j], JLabel.RIGHT);
						lab.setLabelFor(secondarycheckboxes
								.get(secondarycheckboxes.size() - 1));
						labelPanel2.add(lab);
						JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
						p.add(secondarycheckboxes.get(secondarycheckboxes
								.size() - 1));
						// JScrollPane scrollpane = new JScrollPane(p);
						fieldPanel2.add(p);

						temppanel.add(labelPanel2);
						temppanel.add(fieldPanel2);
					}
				} else {

					JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
					fields[i] = new JTextField();
					if (i < tips.length)
						fields[i].setToolTipText(tips[i]);
					if (i < widths.length)
						fields[i].setColumns(widths[i]);

					fields[i].setText(values[i + 1]);

					JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
					lab.setLabelFor(fields[i]);
					labelPanel.add(lab);

					if (i >= 4 && i <= 12) {

						boxes[i - 4] = new JCheckBox();
						if (values[i + 1].equals("Si")) {
							boxes[i - 4].setSelected(true);
						}
						p.add(boxes[i - 4]);
					} else {
						p.add(fields[i]);
					}

					// JScrollPane scrollpane = new JScrollPane(p);

					fieldPanel.add(p);

				}
			}

			// JScrollPane scrollpane = new JScrollPane(temppanel);

			form2.add(scrollpane);

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.FUNCIONARIO_CANCELAR_CONFIRMACION);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.FUNCIONARIO_MODIFICAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);
			
			
			/*JButton confirmar = new JButton("Confirmar");
			confirmar.addActionListener(this);
			confirmar
					.setActionCommand(Constants.FUNCIONARIO_MODIFICAR_CONFIRMACION);
			buttonPanel.add(confirmar);*/

			contentPane.add(form, BorderLayout.NORTH);
			contentPane.add(form2, BorderLayout.CENTER);
			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);

			pack();

			setVisible(true);

		}

		public void actionPerformed(ActionEvent e) {

			String values[];
			boolean maqModifications[];
			boolean validcodigo, validdisponibilidad, validtiempomuerto, indicescheck;

			String command = e.getActionCommand();
			if (command == Constants.FUNCIONARIO_MODIFICAR_CONFIRMACION) {

				validcodigo = true;
				validdisponibilidad = true;
				validtiempomuerto = true;
				indicescheck = true;

				try {
					Integer.parseInt(fields[0].getText());

				} catch (Exception exp) {
					validcodigo = false;
				}

				try {
					Integer.parseInt(fields[4].getText());

				} catch (Exception exp) {
					validdisponibilidad = false;
				}

				try {
					Integer.parseInt(fields[5].getText());

				} catch (Exception exp) {
					validtiempomuerto = false;
				}

				int selected = 0;

				for (int i = 0; i < secondarycheckboxes.size(); i++) {
					if (secondarycheckboxes.get(i).isSelected())
						selected++;
					// System.out.println("selected=" + selected);
				}

				if (selected == 0) {
					indicescheck = false;
				}

				if (validcodigo && indicescheck) {
					values = new String[fields.length + 1];
					maqModifications = new boolean[secondarycheckboxes.size()];
					values[0] = hiddenfield;

					for (int i = 0; i < fields.length; i++) {
						if (i >= 4 && i <= 11) {
							if (boxes[i - 4].isSelected()) {
								values[i + 1] = "1";
							} else {
								values[i + 1] = "0";
							}
						} else {
							values[i + 1] = fields[i].getText();
						}
					}

					for (int i = 0; i < secondarycheckboxes.size(); i++) {
						maqModifications[i] = secondarycheckboxes.get(i)
								.isSelected();
						System.out.println("i=" + i + " value=" + maqModifications[i]);
					}

					db.modifyFuncionario(values, Constants
							.singleArrayListToString(maquinariaValues),
							maqModifications);

					listOfFuncionarios = db.retrieveFuncionarios();
					updateTable();

					modificarFrame.dispose();

				} else {
					JOptionPane
							.showMessageDialog(
									new JFrame(),
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validcodigo ? ""
													: "- Ingrese un numero valido para Codigo\n")
											+ (validdisponibilidad ? ""
													: "- Ingrese un numero valido para Disponibilidad\n")
											+ (validtiempomuerto ? ""
													: "- Ingrese un numero valido para Tiempo Muerto\n")
											+ (indicescheck ? ""
													: "- Seleccione al menos una maquina\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}

			} else if (command == Constants.FUNCIONARIO_CANCELAR_CONFIRMACION) {
				modificarFrame.dispose();
			}
		}
	}
}
